package com.glink.manage.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.glink.common.contants.BaseCodeConstants;
import com.glink.common.exception.GeneralSimpleException;
import com.glink.common.util.BaseCommonUtils;
import com.glink.manage.common.BeanKit;
import com.glink.manage.common.Constants;
import com.glink.manage.domain.OrgBean;
import com.glink.manage.domain.ParticipatingUnitBean;
import com.glink.manage.dto.org.OrgSaveRequestDTO;
import com.glink.manage.dto.org.OrgUpdateRequestDTO;
import com.glink.manage.mapper.OrgMapper;
import com.glink.manage.service.*;
import com.glink.manage.vo.org.OrgBaseInfoVO;
import com.glink.manage.vo.org.OrgIdRequestDTO;
import com.glink.manage.vo.org.OrgInfoVO;
import com.glink.manage.vo.user.UserBaseInfoVO;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.stream.Collectors;

import static java.util.Objects.nonNull;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : qiushaoshan
 * @create 2024/6/18 14:16
 */
@Service
@Slf4j
public class OrgServiceImpl extends ServiceImpl<OrgMapper, OrgBean> implements OrgService {
    
    @Autowired
    @Lazy
    private UserService userService;
    
    @Autowired
    @Lazy
    private ParticipatingUnitService participatingUnitService;
    
    @Autowired
    @Lazy
    private PersonManageService personManageService;
    
    @Autowired
    @Lazy
    private ConstructionWorkService constructionWorkService;
    
    /**
     * 保存组织
     * @param saveRequestDTO 保存数据
     * @return 返回结果
     */
    @Override
    @Transactional(value = "transactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean insertOrg(OrgSaveRequestDTO saveRequestDTO) throws GeneralSimpleException {
        checkPidAndOrgCode(null, saveRequestDTO.getPid(), saveRequestDTO.getOrgCode());
        
        // insert
        final String _Id = BaseCommonUtils.generateUUID();
        OrgBean orgBean = BeanKit.copyProperties(saveRequestDTO, OrgBean::new);
        orgBean.setId(_Id);
        return orgBean.insert();
    }

    /**
     * 修改组织
     * @param updateRequestDTO 保存数据
     * @return 返回结果
     */
    @Override
    @Transactional(value = "transactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean updateOrg(OrgUpdateRequestDTO updateRequestDTO) throws GeneralSimpleException {
        String orgId = updateRequestDTO.getOrgId();
        // update
        if (StringUtils.isNotBlank(orgId)) {
            OrgBean one = findTop(x -> x.eq(OrgBean::getId, orgId));
            if (nonNull(one)) {

                // 判断组织编码是否可用
                checkPidAndOrgCode(orgId, one.getPid(), updateRequestDTO.getOrgCode());
                
                BeanKit.copyPropertiesIgnoreNull(updateRequestDTO, one);
                return update(one, Wrappers.lambdaQuery(OrgBean.class)
                        .eq(OrgBean::getId, orgId)
                );
            }
        }else{
            throw new GeneralSimpleException("402002", orgId);
        }
        return false;
    }

    /**
     * 校验pid和组织编码是否符合要求
     * @param orgId 组织ID
     * @param pid 组织父级ID
     * @param orgCode 组织编码
     * @throws GeneralSimpleException 异常信息
     */
    private void checkPidAndOrgCode(String orgId, String pid, String orgCode) throws GeneralSimpleException {
        // 判断父级是否存在
        if(StringUtils.isNotBlank(pid)){
            OrgBean one = this.lambdaQuery().eq(OrgBean::getId, pid).one();
            if(Objects.isNull(one)){
                throw new GeneralSimpleException("402002", pid);
            }
        }
        
        // 判断组织编码是否可用
        if(StringUtils.isNotBlank(orgCode)){
            List<OrgBean> oneList = this.lambdaQuery().ne(StringUtils.isNotEmpty(orgId), OrgBean::getId, orgId)
                    .eq(OrgBean::getOrgCode, orgCode).list();
            if(CollectionUtils.isNotEmpty(oneList)){
                // 402003=组织编码[{0}]存在相同，不可重复
                throw new GeneralSimpleException("402003", orgCode);
            }
        }
        
    }
    
    /**
     * 删除组织
     *
     * @param orgId 组织ID
     * @return 结果
     */
    @Override
    @Transactional(value = "transactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean delOrg(String orgId) throws GeneralSimpleException {
        LambdaQueryChainWrapper<OrgBean> wrapper = this.lambdaQuery().eq(OrgBean::getId, orgId);

        OrgBean orgBean = wrapper.one();
        // 不存在则无需删除
        if(Objects.isNull(orgBean)){
            return true;
        }
        
        if(StringUtils.isBlank(orgBean.getPid())){
            throw new GeneralSimpleException("402006", orgBean.getName());
        }
        
        // 判断是否存在下级单位，存在则不能删除
        List<OrgBean> oneList = this.lambdaQuery().eq(OrgBean::getPid, orgId).list();
        if(CollectionUtils.isNotEmpty(oneList)){
            throw new GeneralSimpleException("402004", orgBean.getName());
        }
        boolean status = this.removeById(orgId);
        if(status){
            // 组织机构删除，则移除该组织下的所有用户
            status = userService.disOrgByOrgId(orgId);
            if(!status){
                throw new GeneralSimpleException("402005", orgBean.getName());
            }
        }

        return status; 
    }

    /**
     * 获取组织菜单树
     *
     * @return 菜单树
     */
    @Override
    public List<OrgInfoVO> getOrgTree() {
        List<OrgInfoVO> orgInfoVOList = Lists.newArrayList();
        List<OrgBean> orgBeanList = this.list(Wrappers.lambdaQuery(OrgBean.class)
                .isNull(OrgBean::getPid)
                .or()
                .eq(OrgBean::getPid, StringUtils.EMPTY)
                .orderByAsc(OrgBean::getOrgOrder)
                .orderByAsc(OrgBean::getCreateTime)
                .orderByAsc(OrgBean::getId))
                ;
        if(CollectionUtils.isNotEmpty(orgBeanList)){
            orgBeanList.forEach(orgBean -> {
                OrgInfoVO orgInfoVO = new OrgInfoVO();
                BeanKit.copyProperties(orgBean, orgInfoVO);
                orgInfoVO.setOrgId(orgBean.getId());
                
                orgInfoVOList.add(findOrg(orgInfoVO));
            });
        }

        OrgInfoVO orgInfoVO = participatingUnitService.findParticipatingUnitTree();
        if(Objects.nonNull(orgInfoVO)){
            orgInfoVOList.add(orgInfoVO);
        }

        return orgInfoVOList;
    }

    /**
     * 获取所有参建单位ID
     * @return 参建单位ID
     */
    @Override
    public List<String> findAllParticipatingUnitId(){
        return participatingUnitService.getAllId();
    }

    /**
     * 获取所有部门ID
     * @return 部门ID
     */
    @Override
    public List<String> findAllDepartmentId() throws GeneralSimpleException {
        String orgId = BaseCommonUtils.extractOrdIdByToken();
        if(StringUtils.isBlank(orgId)){
            log.info("单位信息不存在");
            throw new GeneralSimpleException("100003");
        }
        String parentIdByOrgId = findParentIdByOrgId(orgId);
        return findOrgTreeIdByOrgId(parentIdByOrgId);
    }

    private String findParentIdByOrgId(String orgId){
        if(StringUtils.isNotBlank(orgId)){
            OrgBean orgBean = this.lambdaQuery().eq(OrgBean::getId, orgId).one();
            if(Objects.nonNull(orgBean)){
                if(StringUtils.isBlank(orgBean.getPid())){
                    return orgBean.getId();
                }else{
                   return findParentIdByOrgId(orgBean.getPid());
                }
            }else{
                return orgId;
            }
        }else{
            return orgId;
        }
    }
    
    /**
     * 查询组织名称
     *
     * @param orgId 组织ID
     * @return 组织名称
     */
    @Override
    public String findOrgNameByOrgId(String orgId) {
        OrgBean one = this.lambdaQuery().eq(OrgBean::getId, orgId).one();
        String orgName = "";
        if(Objects.nonNull(one)){
            orgName = one.getName();
        }
        
        if(StringUtils.isBlank(orgName)){
            orgName = participatingUnitService.findNameByObjId(orgId);
        }
        return orgName;
    }

    /**
     * 根据组织ID查询组织信息
     *
     * @param dto 组织ID
     * @return 组织信息
     */
    @Override
    public OrgBaseInfoVO findById(OrgIdRequestDTO dto) {
        OrgBean one = this.lambdaQuery().eq(OrgBean::getId, dto.getOrgId()).one();
        OrgBaseInfoVO orgInfoVO = null;
        if(Objects.nonNull(one)){
            orgInfoVO = new OrgBaseInfoVO();
            BeanKit.copyProperties(one, orgInfoVO);
            orgInfoVO.setOrgId(one.getId());
        }

        return orgInfoVO;
    }

    /**
     * 根据组织ID查询组织及其下级机构ID
     *
     * @param orgId 组织ID
     * @return 组织树ID
     */
    @Override
    public List<String> findOrgTreeIdByOrgId(String orgId) throws GeneralSimpleException {

        List<String> orgIdList = Lists.newArrayList();
        orgIdList.add(orgId);
        
        // 参建单位组织ID
        if(StringUtils.equals(orgId, Constants.PARTICIPATION_UNIT_ORG_ID)){
            List<String> departmentOrgIdList = getDataPermissionDepartmentOrgId();
            if(CollectionUtils.isEmpty(departmentOrgIdList)){
                return orgIdList;
            }
            return findTreeParticipatingUnitIdByDepartmentOrgId(departmentOrgIdList);
        }else{
            List<OrgBean> orgBeanList = this.lambdaQuery()
                    .eq(OrgBean::getIsAvailable, BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01)
                    .orderByAsc(OrgBean::getOrgOrder)
                    .list();
            if(CollectionUtils.isNotEmpty(orgBeanList)){
                drillOrgTree(orgIdList, orgBeanList);
            }
        }
        return orgIdList;
    }

    /**
     * 数据权限，根据用户单位ID查询权限内的所有单位ID(包括参建单位)
     * @return 单位ID
     */
    @Override
    public List<String> getDataPermissionOrgId() throws GeneralSimpleException {

        String orgId = BaseCommonUtils.extractOrdIdByToken();
        if(StringUtils.isBlank(orgId)){
            log.info("单位信息不存在");
            throw new GeneralSimpleException("100003");
        }
        
        List<String> orgIdList = Lists.newArrayList();
        if(checkDepartmentByOrgId(orgId)){
            // 部门管理员
            orgIdList.addAll(findTreePermissionOrgIdByUserOrgId(orgId));
        }else if(checkParticipatingUnitByOrgId(orgId)){
            // 参建单位
            orgIdList.add(orgId);
        }
        
        if(CollectionUtils.isEmpty(orgIdList)){
            throw new GeneralSimpleException("300012");
        }
        
        return orgIdList;
    }

    /**
     * 查询权限内的所有参建单位ID
     * @return 参建单位ID
     * @throws GeneralSimpleException 异常信息
     */
    public List<String> getDataPermissionParticipatingUnitId() throws GeneralSimpleException {
        return findTreeParticipatingUnitIdByDepartmentOrgId(getDataPermissionDepartmentOrgId());
    }
    public List<String> getDataPermissionParticipatingUnitIdByOrgIdIn(List<String> orgIdList) {
        return findTreeParticipatingUnitIdByDepartmentOrgId(orgIdList);
    }

    /**
     * 从工程中获取所有关联的参建单位ID
     * @return 参建单位ID
     */
    public List<String> getAllParticipatingUnitIdByWork() throws GeneralSimpleException {

        String orgId = BaseCommonUtils.extractOrdIdByToken();
        if(StringUtils.isBlank(orgId)){
            log.info("单位信息不存在");
            throw new GeneralSimpleException("100003");
        }
        
        if(checkParticipatingUnitByOrgId(orgId)){
            List<String> orgIdList = Lists.newArrayList();
            orgIdList.add(orgId);
            return orgIdList;
        }
        
        return findTreeParticipatingUnitIdByDepartmentOrgId(null);
    }

    /**
     * 查询权限内的部门ID
     * @return 所有部门ID
     * @throws GeneralSimpleException 异常信息
     */
    @Override
    public List<String> getDataPermissionDepartmentOrgId() throws GeneralSimpleException {
        String orgId = BaseCommonUtils.extractOrdIdByToken();
        if(StringUtils.isBlank(orgId)){
            log.info("单位信息不存在");
            throw new GeneralSimpleException("100003");
        }

        return findOrgTreeIdByOrgId(findDepartmentOrgIdByOrgId(orgId));
    }

    @Override
    public List<String> getDataPermissionDepartmentOrgId(String orgId) throws GeneralSimpleException {
        if(StringUtils.isBlank(orgId)){
            log.info("单位信息不存在");
            throw new GeneralSimpleException("100003");
        }

        return findOrgTreeIdByOrgId(findDepartmentOrgIdByOrgId(orgId));
    }

    /**
     * 根据用户单位ID查询权限内的所有单位ID(包括参建单位)
     *
     * @param orgId 单位ID
     * @return 单位ID
     */
    @Override
    public List<String> findTreePermissionOrgIdByUserOrgId(String orgId) throws GeneralSimpleException {
        return findTreePermissionOrgIdByDepartmentOrgId(findDepartmentOrgIdByOrgId(orgId));
    }

    /**
     * 根据项目部组织机构ID查询权限内所有的机构ID（包括参建单位）
     * @param orgId 项目部组织机构ID
     * @return 所有的机构ID（包括参建单位）
     */
    private List<String> findTreePermissionOrgIdByDepartmentOrgId(String orgId) throws GeneralSimpleException {

        List<String> orgIdList = findOrgTreeIdByOrgId(orgId);
        orgIdList = orgIdList == null ? Lists.newArrayList() : orgIdList;

        List<String> unitIdList = findTreeParticipatingUnitIdByDepartmentOrgId(orgIdList);
        if(CollectionUtils.isNotEmpty(unitIdList)){
            orgIdList.addAll(unitIdList);
        }
        return orgIdList;
    }

    /**
     * 根据所属单位ID查询范围内的参建单位
     * @param orgIdList 所属单位ID
     * @return 参建单位
     */
    private List<String> findTreeParticipatingUnitIdByDepartmentOrgId(List<String> orgIdList) {

        orgIdList = orgIdList == null ? Lists.newArrayList() : orgIdList;
        
        return this.baseMapper.findAllParticipatingUnitIdByProjectDepartmentObjIdIn(orgIdList);
    }

    /**
     * 根据用户权限查询机构树
     *
     * @return 机构树
     */
    @Override
    public List<OrgInfoVO> getOrgTreeByPermission() throws GeneralSimpleException {
        
        boolean headOffice = userService.checkHeadOffice();
        boolean adminByUser = userService.checkAdminByUser();
        if(headOffice || adminByUser){
            return getOrgTree();
        }

        String orgId = BaseCommonUtils.extractOrdIdByToken();
        if(StringUtils.isBlank(orgId)){
            throw new GeneralSimpleException("100003");
        }
        
        List<OrgInfoVO> orgInfoVOList = Lists.newArrayList();
        // 校验是否是项目部
        if(checkDepartmentByOrgId(orgId)){
            String departmentOrgId = findDepartmentOrgIdByOrgId(orgId);
            OrgBean orgBean = this.lambdaQuery()
                    .eq(OrgBean::getId, departmentOrgId).one();
            if(Objects.nonNull(orgBean)){
                OrgInfoVO orgInfoVO = new OrgInfoVO();
                BeanKit.copyProperties(orgBean, orgInfoVO);
                orgInfoVO.setOrgId(orgBean.getId());
                // 查询子节点
                OrgInfoVO org = findOrg(orgInfoVO);
                // 查询父节点
                orgInfoVOList.add(findParentByOrgId(org.getPid(), org));
            }

            List<String> allOrgIdList = findTreePermissionOrgIdByDepartmentOrgId(departmentOrgId);
            if(CollectionUtils.isNotEmpty(allOrgIdList)){
                OrgInfoVO orgInfoVO = participatingUnitService.findParticipatingUnitTreeByIdIn(allOrgIdList);
                if(Objects.nonNull(orgInfoVO)){
                    orgInfoVOList.add(orgInfoVO);
                }
            }
            return orgInfoVOList;
            
        }else{
            // 校验是否是参建单位
            if(checkParticipatingUnitByOrgId(orgId)){
                boolean generalContractingUnit = userService.checkGeneralContractingUnit();
                if(generalContractingUnit){
                    List<String> workIdList = constructionWorkService.findGeneralContractingUnitAccessWorkId();
                    if(CollectionUtils.isNotEmpty(workIdList)){
                        List<String> participatingUnitObjIdList = constructionWorkService.findGeneralContractingUnitParticipatingUnitObjIdByObjIdIn(workIdList);
                        if(CollectionUtils.isNotEmpty(participatingUnitObjIdList)){
                            // 参建单位
                            OrgInfoVO orgInfoVO = participatingUnitService.findParticipatingUnitTreeByIdIn(participatingUnitObjIdList);
                            orgInfoVOList.add(orgInfoVO);
                            return orgInfoVOList;
                        }
                    }
                }
                
                // 参建单位
                OrgInfoVO orgInfoVO = participatingUnitService.findParticipatingUnitTreeByIdIn(Collections.singletonList(orgId));
                orgInfoVOList.add(orgInfoVO);
                return orgInfoVOList;
            }
        }

        return orgInfoVOList;
    }

    @Override
    public List<OrgInfoVO> getDepartmentOrgTreeByPermission() throws GeneralSimpleException {

        String orgId = BaseCommonUtils.extractOrdIdByToken();
        if(StringUtils.isBlank(orgId)){
            throw new GeneralSimpleException("100003");
        }

        List<OrgInfoVO> orgInfoVOList = Lists.newArrayList();
        // 校验是否是项目部
        if(checkDepartmentByOrgId(orgId)){
            String departmentOrgId = findDepartmentOrgIdByOrgId(orgId);
            OrgBean orgBean = this.lambdaQuery()
                    .eq(OrgBean::getId, departmentOrgId).one();
            if(Objects.nonNull(orgBean)){
                OrgInfoVO orgInfoVO = new OrgInfoVO();
                BeanKit.copyProperties(orgBean, orgInfoVO);
                orgInfoVO.setOrgId(orgBean.getId());
                // 查询子节点
                OrgInfoVO org = findDepartmentOrg(orgInfoVO);
                // 查询父节点
                orgInfoVOList.add(findParentByOrgId(org.getPid(), org));
            }
            return orgInfoVOList;
        }
        return orgInfoVOList;
    }

    /**
     * 根据单位信息查询所属项目部机构
     * @param orgId 机构ID
     * @return 机构ID
     */
    @Override
    public String findDepartmentOrgIdByOrgId(String orgId){
        if(StringUtils.isNotBlank(orgId)){
            OrgBean orgBean = this.lambdaQuery().eq(OrgBean::getId, orgId).one();
            if(Objects.nonNull(orgBean)){
                if(StringUtils.equals(orgBean.getIfEngDepartment(), BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01)){
                    return orgBean.getId();    
                }else{
                    if(StringUtils.isNotBlank(orgBean.getPid())){
                        return findDepartmentOrgIdByOrgId(orgBean.getPid());
                    }else{
                        return orgId;
                    }
                }
            }else{
                return orgId;
            }
        }else{
            return orgId;
        }
    }
    
    /**
     * 根据单位ID查询上级单位
     * @param orgId 单位ID
     * @return 单位信息
     */
    private OrgInfoVO findParentByOrgId(String orgId, OrgInfoVO tempOrgInfo){
        if(StringUtils.isNotBlank(orgId)){
            OrgBean orgBean = this.lambdaQuery().eq(OrgBean::getId, orgId).one();
            if(Objects.nonNull(orgBean)){
                OrgInfoVO orgInfoVO = new OrgInfoVO();
                BeanKit.copyProperties(orgBean, orgInfoVO);
                orgInfoVO.setOrgId(orgBean.getId());
                orgInfoVO.setChildrenList(Collections.singletonList(tempOrgInfo));
                return findParentByOrgId(orgInfoVO.getPid(), orgInfoVO);
            }else{
                return tempOrgInfo;
            }
        }else{
            return tempOrgInfo;
        }
    }

    @Override
    public OrgBean findRootNodeByOrgId(String orgId){
        if(StringUtils.isNotBlank(orgId)){
            OrgBean orgBean = this.lambdaQuery().eq(OrgBean::getId, orgId).one();
            if(Objects.nonNull(orgBean)){
                if(StringUtils.isBlank(orgBean.getPid())){
                    return orgBean;
                }
                return findRootNodeByOrgId(orgBean.getPid());
            }else{
                return null;
            }
        }else{
            return null;
        }
    }
    
    /**
     * 校验是否为部门
     * @return 状态
     */
    @Override
    public boolean checkDepartment() throws GeneralSimpleException {
        String orgId = BaseCommonUtils.extractOrdIdByToken();
        if(StringUtils.isBlank(orgId)){
            throw new GeneralSimpleException("100003");
        }
        return checkDepartmentByOrgId(orgId);
    }
    @Override
    public boolean checkDepartmentByOrgId(String orgId){
        Integer count = this.lambdaQuery().eq(OrgBean::getId, orgId).count();
        return Objects.nonNull(count) && count > 0;
    }

    @Override
    public boolean checkParticipatingUnit() throws GeneralSimpleException {
        String orgId = BaseCommonUtils.extractOrdIdByToken();
        if(StringUtils.isBlank(orgId)){
            throw new GeneralSimpleException("100003");
        }
        return checkParticipatingUnitByOrgId(orgId);
    }
    /**
     * 校验是否为参建单位
     * @param orgId 单位ID
     * @return 状态
     */
    @Override
    public boolean checkParticipatingUnitByOrgId(String orgId){
        Integer count = participatingUnitService.lambdaQuery()
                .eq(ParticipatingUnitBean::getObjId, orgId)
                .count();
        return Objects.nonNull(count) && count > 0;
    }

    /**
     * 根据用户信息查询项目部ID
     *
     * @return 项目部ID
     */
    @Override
    public String getDepartmentOrgIdByUserId() throws GeneralSimpleException {

        boolean projectDepartment = userService.checkProjectDepartment();
        if(projectDepartment){
            String userId = BaseCommonUtils.extractUserIdtByToken();
            if(StringUtils.isBlank(userId)){
                throw new GeneralSimpleException("100003");
            }
            UserBaseInfoVO userBaseInfoVO = userService.findById(userId);
            if(Objects.nonNull(userBaseInfoVO)){
                String orgId = userBaseInfoVO.getOrgId();
                if(StringUtils.isNotBlank(orgId)){
                    return findDepartmentOrgIdByOrgId(orgId);
                }
            }
        }

        return null;
    }

    @Override
    public String getDepartmentOrgIdByUserId(String userId) throws GeneralSimpleException {

        boolean projectDepartment = userService.checkProjectDepartment(userId);
        if(projectDepartment){
            if(StringUtils.isBlank(userId)){
                throw new GeneralSimpleException("100003");
            }
            UserBaseInfoVO userBaseInfoVO = userService.findById(userId);
            if(Objects.nonNull(userBaseInfoVO)){
                String orgId = userBaseInfoVO.getOrgId();
                if(StringUtils.isNotBlank(orgId)){
                    return findDepartmentOrgIdByOrgId(orgId);
                }
            }
        }

        return null;
    }

    /**
     * 根据用户信息和所属项目部ID查询工程现场
     *
     * @param departmentAdminOrgId 项目部ID
     * @param userId               用户ID
     * @return 施工现场ID
     */
    @Override
    public List<String> findWorkSiteByDepartmentAdminOrgIdAndSuperintendent(String departmentAdminOrgId, String userId) throws GeneralSimpleException {
        // departmentAdminOrgId 为空，说明不是项目管理员，只需要查询责任人
        List<String> dataPermissionDepartmentOrgIdList;
        String personObjId = personManageService.findObjIdByAccountObjId(userId);
        
        if(StringUtils.isEmpty(departmentAdminOrgId)){
            if(StringUtils.isEmpty(personObjId)){
                return Lists.newArrayList();
            }
            // 负责人
            return this.baseMapper.findWorkSiteBySuperintendent(personObjId);
        }else{
            // 项目管理员
            dataPermissionDepartmentOrgIdList = getDataPermissionDepartmentOrgId(departmentAdminOrgId);
            if(CollectionUtils.isNotEmpty(dataPermissionDepartmentOrgIdList)){
                return this.baseMapper.findWorkSiteByDepartmentAdminOrgIdIn(dataPermissionDepartmentOrgIdList);
            }else{
                if(StringUtils.isEmpty(personObjId)){
                    return Lists.newArrayList();
                }
                return this.baseMapper.findWorkSiteBySuperintendent(personObjId);
            }
        }
    }

    /**
     * 查询参建单位树
     *
     * @return 参建单位
     */
    @Override
    public List<OrgInfoVO> getUnitTree() throws GeneralSimpleException {
        String orgId = BaseCommonUtils.extractOrdIdByToken();
        if(StringUtils.isBlank(orgId)){
            throw new GeneralSimpleException("100003");
        }

        List<OrgInfoVO> orgInfoVOList = Lists.newArrayList();
        
        // 校验是否是项目部
        if(checkDepartmentByOrgId(orgId)){
            OrgInfoVO orgInfoVO1 = participatingUnitService.findParticipatingUnitTree();
            if(Objects.nonNull(orgInfoVO1)){
                orgInfoVOList.add(orgInfoVO1);
            }
            return orgInfoVOList;

        }else{
            // 校验是否是参建单位
            if(checkParticipatingUnitByOrgId(orgId)){
                // 参建单位
                OrgInfoVO orgInfoVO = participatingUnitService.findParticipatingUnitTreeByIdIn(Collections.singletonList(orgId));
                orgInfoVOList.add(orgInfoVO);
                return orgInfoVOList;
            }
        }

        return orgInfoVOList;
    }

    /**
     * 查询所有上级单位
     *
     * @param orgId 单位ID
     * @return 单位ID
     */
    @Override
    public List<String> findAllParentObjIdByOrgId(String orgId) {
        List<String> orgIdList = Lists.newArrayList();
        orgIdList.add(orgId);
        while (true){
            String parentId = findParentIdByOrgId(orgId);
            
            if(StringUtils.isEmpty(parentId) || StringUtils.equals(orgId, parentId)){
                break;
            }

            orgIdList.add(parentId);
            orgId = parentId;
        }
        return orgIdList;
    }


    /**
     * 根据用户权限查询机构树
     *
     * @return 机构树
     */
//    @Deprecated
//    public List<OrgInfoVO> getOrgTreeByPermissionBak() throws GeneralSimpleException {
//        
//        String orgId = BaseCommonUtils.extractOrdIdByToken();
//        if(StringUtils.isBlank(orgId)){
//            throw new GeneralSimpleException("100001");
//        }
//        
//        UserPermissionInfoVO permissionInfoVO = userService.findPermissionByUserId(BaseCommonUtils.extractUserIdtByToken());
//
//        List<OrgInfoVO> orgInfoVOList = Lists.newArrayList();
//        if(permissionInfoVO.isHeadOffice() || permissionInfoVO.isSystemAdmin()){
//            return getOrgTree();
//        }else if(permissionInfoVO.isProjectDepartment()){
//            // 部门管理员
//            List<OrgBean> orgBeanList = this.list(Wrappers.lambdaQuery(OrgBean.class)
//                    .eq(OrgBean::getId, orgId)
//                    .orderByAsc(OrgBean::getOrgOrder)
//                    .orderByAsc(OrgBean::getCreateTime)
//                    .orderByAsc(OrgBean::getId));
//            if(CollectionUtils.isNotEmpty(orgBeanList)){
//                orgBeanList.forEach(orgBean -> {
//                    OrgInfoVO orgInfoVO = new OrgInfoVO();
//                    BeanKit.copyProperties(orgBean, orgInfoVO);
//                    orgInfoVO.setOrgId(orgBean.getId());
//
//                    orgInfoVOList.add(findOrg(orgInfoVO));
//                });
//            }
//
//            List<String> allOrgIdList = findPermissionOrgIdByUserOrgId(orgId);
//            if(CollectionUtils.isNotEmpty(allOrgIdList)){
//                OrgInfoVO orgInfoVO = participatingUnitService.findParticipatingUnitTreeByIdIn(Collections.singletonList(orgId));
//                if(Objects.nonNull(orgInfoVO)){
//                    orgInfoVOList.add(orgInfoVO);    
//                }
//            }
//            return orgInfoVOList;
//        }else if(permissionInfoVO.isParticipatingUnit()){
//            // 参建单位
//            OrgInfoVO orgInfoVO = participatingUnitService.findParticipatingUnitTreeByIdIn(Collections.singletonList(orgId));
//            orgInfoVOList.add(orgInfoVO);
//            return orgInfoVOList;
//        }
//        return orgInfoVOList;
//    }

    private void drillOrgTree(List<String> orgIdList, List<OrgBean> orgBeanList){
        List<String> temp = orgBeanList.stream()
                .filter(orgBean -> orgIdList.contains(orgBean.getPid()) && !orgIdList.contains(orgBean.getId()))
                .map(OrgBean::getId).distinct().collect(Collectors.toList());
        if(CollectionUtils.isNotEmpty(temp)){
            orgIdList.addAll(temp);

            drillOrgTree(orgIdList, orgBeanList);
        }
    }

    /**
     * 递归查询组织树
     * @param orgInfoVO 组织
     * @return 组织
     */
    private OrgInfoVO findOrg(OrgInfoVO orgInfoVO){
        List<OrgBean> childrenOrgList = this.list(Wrappers.lambdaQuery(OrgBean.class)
                .eq(OrgBean::getPid, orgInfoVO.getOrgId())
                .orderByAsc(OrgBean::getOrgOrder)
                .orderByAsc(OrgBean::getCreateTime)
                .orderByAsc(OrgBean::getId));
        if(CollectionUtils.isNotEmpty(childrenOrgList)){
            List<OrgInfoVO> childrenOrgVOList = Lists.newArrayList();
            childrenOrgList.forEach(childrenOrg -> {
                OrgInfoVO childrenOrgVO = new OrgInfoVO();
                BeanKit.copyProperties(childrenOrg, childrenOrgVO);
                childrenOrgVO.setOrgId(childrenOrg.getId());
                
                childrenOrgVOList.add(findOrg(childrenOrgVO));
            });
            orgInfoVO.setChildrenList(childrenOrgVOList);
        }
        return orgInfoVO;
    }

    private OrgInfoVO findDepartmentOrg(OrgInfoVO orgInfoVO){
        List<OrgBean> childrenOrgList = this.list(Wrappers.lambdaQuery(OrgBean.class)
                .eq(OrgBean::getPid, orgInfoVO.getOrgId())
                .eq(OrgBean::getIfEngDepartment, BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01)
                .orderByAsc(OrgBean::getOrgOrder)
                .orderByAsc(OrgBean::getCreateTime)
                .orderByAsc(OrgBean::getId));
        if(CollectionUtils.isNotEmpty(childrenOrgList)){
            List<OrgInfoVO> childrenOrgVOList = Lists.newArrayList();
            childrenOrgList.forEach(childrenOrg -> {
                OrgInfoVO childrenOrgVO = new OrgInfoVO();
                BeanKit.copyProperties(childrenOrg, childrenOrgVO);
                childrenOrgVO.setOrgId(childrenOrg.getId());

                childrenOrgVOList.add(findOrg(childrenOrgVO));
            });
            orgInfoVO.setChildrenList(childrenOrgVOList);
        }
        return orgInfoVO;
    }
    
    /**
     * 获取一条组织信息
     * @param consumer 查询条件
     * @return 组织
     */
    private OrgBean findTop(Consumer<LambdaQueryWrapper<OrgBean>> consumer) {
        return lambdaQuery()
                .and(Objects.nonNull(consumer), consumer)
                .last(" LIMIT 1 ")
                .one();
    }

    /**
     * 校验用户单位信息
     *
     * @param orgId 用户单位
     * @return 状态
     */
    @Override
    public boolean checkOrg(String orgId) {
        if(StringUtils.isBlank(orgId)){
            return false;
        }
        Integer num = this.baseMapper.countOrgByOrgId(orgId);
        return Objects.nonNull(num) && num > 0;
    }
}
